/**
 * 
 */
package org.ccay.core.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Locale;
import java.util.Map;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.exception.impl.CommonApplicationException;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.registry.IRegistryManager;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * freemaker模版解析辅助类
 * 
 */
public final class TemplateUtil {

	private TemplateUtil() {

	}

	/**
	 * 
	 */
	private static final Configuration configuration = new Configuration();
	
	static{
		//设置内部编码
		configuration.setEncoding(Locale.getDefault(), EncodingUtil.UTF_8);
	}
	
	/*
	 * 1分钟
	 */
	private static final int TIME_BUFFER = 60000;
	/**
	 * 把变量内容填充进模版文件内容
	 * 
	 * @param templateStr
	 *            模版内容
	 * @param model
	 *            变量
	 * @param templateType
	 *            类型,如mobileJson
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String putDataIntoTemplate(String templateStr, Object model,
			String templateType) throws IOException, TemplateException {
		StringReader reader=new StringReader(templateStr);
		try {
			return FreeMarkerTemplateUtils.processTemplateIntoString(
					new Template(templateType, reader, configuration,
							EncodingUtil.UTF_8), model);
		} finally {
			StreamUtil.closeStreams(reader);
		}
	}
	
	/**
	 * 创建模板
	 * 
	 * @param name
	 *            名称
	 * @param templateStr
	 *            模板内容
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static Template createTemplate(String name, String templateStr) throws IOException, TemplateException {
		return createTemplate(name, new StringReader(templateStr));
	}
	
	 
	/**
	 * 创建模板
	 * @param name
	 * @param templateStr
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static Template createTemplate(String name, Reader reader) throws IOException, TemplateException {
		try {
			return new Template(name, reader, configuration, EncodingUtil.UTF_8);
		} finally {
			StreamUtil.closeStreams(reader);
		}
	}
	
	/**
	 *  把变量内容填充进mobile模版文件内容
	 * @param templateStr
	 * @param variables
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String putDataIntoTemplateForMobile(String templateStr,
			Map<String, Object> variables) throws IOException,
			TemplateException {

		return putDataIntoTemplate(templateStr, variables, "mobileJson");
	}
	
	/**
	 *  把变量内容填充进mobile模版文件内容
	 * @param templateStr
	 * @param variables
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String putDataIntoTemplate(String templateStr,
			Map<String, Serializable> variables) throws IOException,
			TemplateException {
		return putDataIntoTemplate(templateStr, variables, null);
	}
	/**
	 * 获取模板ftl的名称
	 * @return
	 * @param isSubject 是否主题
	 * Created：2012-12-6
	 * @author chaowangbang
	 */
	public static String getTemplateFileName(String type,String name,boolean isSubject){
		if(isSubject){
			return type + "_" + name + "Subject.ftl";
		}else{
			return type + "_" + name + ".ftl";
		}
	}
	/**
	 * 生成ftl文件
	 * 
	 * @param outFileName
	 * @param content
	 * @param path
	 * @throws ApplicationException
	 * @throws IOException 
	 */
	public static void createFtl(String outFile, String content, long modifiedTime) 
	   throws ApplicationException{
		OutputStreamWriter ow = null;
		FileOutputStream fo = null;
		if(StringUtil.isNullOrEmpty(outFile)){
			return;
		}
		try {
			// 创建文件
			File file = new File(outFile);
			// 文件不存在则创建，若存在且ftl修改时间小于富文本模板修改时间则创建
			if (!file.exists()) {
				file.createNewFile();
				fo = new FileOutputStream(file);
				ow = new OutputStreamWriter(fo,EncodingUtil.UTF_8);
				ow.write(content);
			} else{
				// ftl的最后修改时
				long ftlModified = file.lastModified();
				if (ftlModified - modifiedTime < - TIME_BUFFER) {
					fo = new FileOutputStream(file);
					ow = new OutputStreamWriter(fo,EncodingUtil.UTF_8);
					ow.write(content);
				}
			} 
		 }catch (IOException e) {
			 throw new CommonApplicationException("ccay.core.00020008",e);
		 }finally{
			 StreamUtil.closeStreams(fo);
			 StreamUtil.closeStreams(ow);
		 }
	}
	
	public static void putAppRoot(Map<String,Serializable> bindItems){
		//把应用root放变量中
		String appRootUrl = Ccay.getContext().getBean("registryManager", IRegistryManager.class).getValue("AppRootUrl");;
		String appRoot = null;
		//如果数据字典配置的是以#！结尾的地址 判断截取
		if(!StringUtil.isNullOrEmpty(appRootUrl) && appRootUrl.endsWith("/#!")){
			appRoot = appRootUrl.substring(0,appRootUrl.length()-3);
		}else{
			appRoot = appRootUrl;
		}
		//把应用root放变量中
		bindItems.put("appRoot", appRoot);
		bindItems.put("appRootUrl", appRootUrl);
	}
	
}
